package com.shs.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shs.sys.common.*;
import com.shs.sys.entity.Permission;
import com.shs.sys.entity.Role;
import com.shs.sys.entity.User;
import com.shs.sys.service.PermissionService;
import com.shs.sys.service.RoleService;
import com.shs.sys.vo.RoleVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  角色前端控制器
 * </p>
 *
 * @author jxm
 * @since 2020-04-14
 */
@RestController
@RequestMapping("role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    /**
     * 查询角色
     * @return
     */
    @RequestMapping("loadAllRole")
    public DataGridView loadAllRole(RoleVo vo){
        Page<Role> page = new Page<>(vo.getPage(),vo.getLimit());
        QueryWrapper<Role> wrapper = new QueryWrapper();
        wrapper.like(StringUtils.isNotBlank(vo.getName()),"name",vo.getName());
        wrapper.like(StringUtils.isNotBlank(vo.getRemark()),"remark",vo.getRemark());
        wrapper.eq(vo.getAvailable()!=null,"available",vo.getAvailable());
        wrapper.orderByDesc("createtime");
        roleService.page(page,wrapper);
        return new DataGridView(page.getTotal(),page.getRecords());

    }

    /**
     * 添加角色
     * @param vo
     * @return
     */
    @RequestMapping("addRole")
    public ResultObj addRole(RoleVo vo){
        try {
            vo.setCreatetime(new Date());
            roleService.save(vo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 修改角色
     * @param vo
     * @return
     */
    @RequestMapping("updateRole")
    public ResultObj updateRole(RoleVo vo){
        try {
            roleService.updateById(vo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("deleteRole")
    public ResultObj deleteRole(Integer id){
        try {
            roleService.removeById(id);
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    /**
     * 根据角色ID加载菜单和权限的树的json串
     * @param roleId
     * @return
     */
    @RequestMapping("initPermissionByRoleId")
    public DataGridView initPermissionByRoleId(Integer roleId){
        //查询所有可用的菜单和权限
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("available",Constants.AVAILABLE_TRUE);
        List<Permission> allPermissions  = permissionService.list(queryWrapper);
        /**
         * 1、根据角色ID查询当前角色拥有的所有的权限或菜单ID
         * 2、根据查询出来的菜单ID查询权限和菜单数据
         */
        List<Integer> ids = roleService.queryRolePermissionIdsByRid(roleId);
        List<Permission> currentPermissions=null;
        if(ids!=null && ids.size()>0){ //如果有ID就去查询
            queryWrapper.in("id",ids);
            currentPermissions = permissionService.list(queryWrapper);
        }else{
            currentPermissions = new ArrayList<>();
        }
        //构造 List<TreeNode>
        List<TreeNode> nodes = new ArrayList<>();
        for (Permission p1 : allPermissions) {
            String checkArr = "0";
            for (Permission p2 : currentPermissions) {
                if(p1.getId()==p2.getId()){
                    checkArr = "1";
                    break;
                }
            }
            Boolean spread = (p1.getOpen()==null||p1.getOpen()==1)?true:false;
            nodes.add(new TreeNode(p1.getId(),p1.getPid(),p1.getTitle(),spread,checkArr));
        }
        return new DataGridView(nodes);
    }

    /**
     * 保存角色和菜单权限之间的关系
     * @param rid
     * @param ids
     * @return
     */
    @RequestMapping("saveRolePermission")
    public ResultObj saveRolePermission(Integer rid,Integer[] ids){
        try {
            roleService.saveRolePermission(rid,ids);
            return ResultObj.DISPATCH_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DISPATCH_ERROR;
        }
    }

}
